﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CRL.Data;
using CRL.Transaction;
using CRL.Transaction.DbStatus;
namespace app31.test
{
    class TransInfoManage : BaseProvider<TransMasterInfo>,ITransInfoManage
    {
        public TransMasterInfo QueryChek(TransOptions option)
        {
            return QueryItem(b => b.CheckKey == option.CheckKey);
        }
        public List<TransMasterInfo> QueryChecks(string projectName)
        {
            var db = GetDBExtend();
            return db.QueryList<TransMasterInfo>(b => b.Status != TransStatus.Canceled && b.Status != TransStatus.Commited && b.ProjectName == projectName);
        }
        public void DeleteCompleted()
        {
            var db = GetDBExtend();
            var all = db.QueryList<TransMasterInfo>(b => b.Status == TransStatus.Canceled || b.Status == TransStatus.Commited);
            if (!all.Any())
            {
                return;
            }
            var tids = all.Select(b => b.TId);
            db.Delete<TransMasterInfo>(b => tids.Contains(b.TId));
            db.Delete<TransStepInfo>(b => tids.Contains(b.TId));
        }
        public void UpdateStatus(string tId, TransStatus status, string msg)
        {
            var db = GetDBExtend();
            db.Update<TransMasterInfo>(b => b.TId == tId, new { Status = status, StatusName = status.ToString(), UpdateTime = DateTime.Now, Msg = msg });
        }
        public new void CreateTable()
        {
            var db = GetDBExtend();
            db.CheckTableCreated(typeof(TransMasterInfo));
            db.CheckTableCreated(typeof(TransStepInfo));
        }
        public List<TransStepInfo> QuerySteps(IEnumerable<string> tIds)
        {
            var db = GetDBExtend();
            return db.QueryList<TransStepInfo>(b => tIds.Contains(b.TId));
        }
        public void UpdateStatus(string tId, int stepIndex, TransStatus status, string msg)
        {
            var db = GetDBExtend();
            var step = stepIndex + 1;
            var c = new ParameCollection();
            c["Status"] = status;
            c["StatusName"] = status.ToString();
            c["UpdateTime"] = DateTime.Now;
            c["Msg"] = msg;
            db.Update<TransStepInfo>(b => b.TId == tId && b.Step == step, c);
        }
        public bool SaveSteps(TransMasterInfo info, List<TransStepInfo> steps, out string error)
        {
            error = "";
            var db = GetDBExtend();
            db.BeginTran();
            try
            {
                db.InsertFromObj(info);
                db.BatchInsert(steps);
                db.CommitTran();
                return true;
            }
            catch (Exception e)
            {
                error = e.Message;
                db.RollbackTran();
                return false;
            }
        }
    }
}
